import { Button, message, Table, Tag } from 'antd';
import React from 'react';
import { connect } from 'umi';

import SearchForm from './SearchForm';

const currControl = 'Edu_Course';
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      dataSource: [],
      totalCount: 0,
      cascaderOption: [],
      datas: [],
      typeRadio:'radio',
      selectedRowKeys:[],
      selectedRowData: [],
    };
  }
  componentDidMount() {
    this.getCourseList();
    this.fetchCategory();
    if(this.props.editStatus =="expand"){
      this.setState({typeRadio:'checkbox'})
    }
  }
  // 课程list
  getCourseList = () => {
    const { params, pageIndex, pageSize } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          SkipCount: (pageIndex - 1) * pageSize,
          MaxResultCount: pageSize,
          ...params,
        },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          this.setState({
            dataSource: resp.result.items,
            loading: false,
            totalCount: resp.result.totalCount,
          });
        }
      });
  };
  //分类
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'course' },
      })
      .then(() => {
        this.setState({ cascaderOption: this.props.Category.response.result });
      });
  };
  /**
   * @param values 搜索信息
   */
  handleSearch = (values: any) => {
    const { keywords, cateid, ageRge } = values;
    this.setState(
      {
        params: { keywords, cateid, ageRge },
        loading: true,
      },
      this.getCourseList,
    );
  };
  //选择课程
  // onSelectChange = (selectedRowKeys: any, values: any) => {
  //   if (this.props.onSelectChange) {
  //     this.props.onSelectChange(values);
  //   }
  //   this.setState({ selectedRowKeys, selectedRowData: values });
  // };
  //添加拓展课程
  handleAdd = () => {
    const { datas,selectedRowData } = this.state;
    let course = this.props.id;
    var params: any = [];
    if (datas && this.props.editStatus !=="expand") {
      this.props.getCourse(datas);
      message.success('保存成功！');
    }
    if(this.props.editStatus =="expand"){
      this.setState({typeRadio:'checkbox'})
      // ,()=>{
        if (selectedRowData.length < 1) {
          message.warning('请至少选择一项！');
        } else {
          selectedRowData.forEach((item: any) => {
            var obj = {
              courseId:course,
              //courseExpandId给此产品添加课程
              //courseId课程id
              courseExpandId: item.id,
              orderId: 0,
            };
            params.push(obj);
          });
          this.props
            .dispatch({
              type: 'Abp/createExpand',
              payload: params,
            })
            .then(() => {
              const resp = this.props.response;
              if (resp.success == true) {
                message.success('添加成功！');
                this.props.getExpandList(course);
              } else {
                message.error('添加失败，请重试！');
              }
            });
        }
      // }
    }
  };
  render() {
    const { cascaderOption, loading, dataSource, totalCount, pageSize,typeRadio } = this.state;
    const rowSelection = {
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        var datas = selectedRows[0];
        this.setState({ datas });
        this.setState({ selectedRowKeys, selectedRowData: selectedRows });
        // this.formRef.current.setFieldsValue({ Role: datas });
      },
      getCheckboxProps: (record: any) => ({
        name: record.name,
      }),
    };
    const columns = [
      {
        title: '课程名称',
        dataIndex: 'title',
        width: 130,
        ellipsis: true,
      },
      {
        title: '分类',
        width: 80,
        dataIndex: 'categoryName',
        ellipsis: true,
      },
      {
        title: '审核状态',
        dataIndex: 'apprvStaus',
        width: 100,
        render: (text: string) => (
          <Tag color={text == 'A' ? 'green' : text == 'U' ? 'blue' : 'red'}>
            {text == 'A' ? '已审核' : text == 'U' ? '未审核' : '审核不通过'}
          </Tag>
        ),
      },
    ];
    return (
      <>
        <SearchForm onSearch={this.handleSearch} treeData={cascaderOption}>
          <Button danger onClick={this.handleAdd} style={{ marginLeft: 12 }}>
            添加
          </Button>
        </SearchForm>
        <Table
          rowKey="id"
          loading={loading}
          rowSelection={{
            type: typeRadio,
            ...rowSelection,
          }}
          columns={columns}
          dataSource={dataSource}
          scroll={{ y: 500 }}
          pagination={{
            onChange: (page, pageSize) => {
              this.setState({ pageIndex: page, pageSize }, () => {
                this.getCourseList();
              });
            },

            pageSize: pageSize,
            pageSizeOptions: ['10', '50', '100', '5000'],
            total: totalCount,
          }}
        />
      </>
    );
  }
}

export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(ViewPage);
